package com.lightsaber.trade.cloth.dao.planning;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.Page;

import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.cloth.dao.category.CategoryDao;
import com.lightsaber.trade.cloth.entity.planning.Planning;
import com.lightsaber.trade.cloth.entity.planning.PlanningLevel;
import com.lightsaber.trade.cloth.entity.planning.PlanningStatus;

@Component
public class PlanningDao extends BaseDao<Planning, String> {
    private final static Logger LOG = LoggerFactory.getLogger(CategoryDao.class);

    public List<Planning> findByCategoryIdAndPlanningLevel(final String categoryId,
            final PlanningLevel planningLevel) {
        eq("category.id", categoryId);
        eq("planningLevel", planningLevel);
        return list();
    }

    public Planning findByPlanningExerciseAndLevel(final Integer planningExercise,
            final PlanningLevel planningLevel) {

        eq("planningLevel", planningLevel);
        if (planningLevel == null) {
            ne("planningLevel", PlanningLevel.FirstLevel);
        }

        createAlias("category", "c");
        eq("c.planYear", planningExercise);

        LOG.info("Find by PlanningExercise({}) and Level({})", planningExercise, planningLevel);
        return unique();
    }

    public Page<Planning> findPage(final Planning planning, final Page<Planning> page) {

        eq("planningLevel", planning.getPlanningLevel());
        eq("isArchivedImage", Boolean.FALSE);
        if (planning.getPlanningLevel() == null) {
            ne("planningLevel", PlanningLevel.FirstLevel);
        }

        createAlias("category", "c");
        eq("c.planYear", planning.getCategory().getPlanYear());
        return findPage(page);
    }

    public Page<Planning> findPage(final Integer planningExercise,
            final PlanningLevel planningLevel, final Boolean isArchivedImage,
            final Page<Planning> page) {

        eq("isArchivedImage", isArchivedImage);
        eq("planningLevel", planningLevel);
        ne("status", PlanningStatus.WaitingForSubmission);
        createAlias("category", "c");
        eq("c.planYear", planningExercise);

        return findPage(page);
    }

    public Planning findByCategoryIdAndLevel(final String categoryId,
            final PlanningLevel planningLevel) {
        eq("category.id", categoryId);
        eq("planningLevel", planningLevel);
        List<Planning> list = list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
}
